#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AI营销方案生成系统 - AI对话路由
功能：处理AI对话和方案生成相关的API请求
作者：AI营销系统开发团队
创建时间：2024
"""

from flask import Blueprint, jsonify, request
from typing import Dict, Any
import logging

from services.chat_service import ChatService
from utils.response_helper import success_response, error_response
from utils.validators import validate_required_fields

# 创建蓝图
chat_bp = Blueprint('chat', __name__)

# 初始化服务
chat_service = ChatService()


@chat_bp.route('/chat/session', methods=['POST'])
def create_session():
    """
    创建聊天会话
    
    Returns:
        JSON: 会话创建结果响应
    """
    try:
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['requirement_id']
        validation_error = validate_required_fields(data, required_fields)
        if validation_error:
            return error_response(
                message='请求参数错误',
                error=validation_error,
                status_code=400
            )
        
        # 创建会话
        import uuid
        session_id = f"session_{uuid.uuid4().hex[:8]}"
        
        # 这里可以添加会话创建的业务逻辑
        # 比如保存到数据库等
        
        return success_response(
            data={
                'session_id': session_id,
                'requirement_id': data['requirement_id'],
                'status': 'created'
            },
            message='会话创建成功',
            status_code=201
        )
        
    except Exception as e:
        logging.error(f"创建会话失败: {str(e)}")
        return error_response(
            message='创建会话失败',
            error=str(e),
            status_code=500
        )


@chat_bp.route('/chat/generate', methods=['POST'])
def generate_content():
    """
    生成AI营销方案内容
    
    Returns:
        JSON: 生成结果响应
    """
    try:
        data = request.get_json()
        
        # 验证必填字段
        required_fields = ['requirement_id', 'session_id']
        validation_error = validate_required_fields(data, required_fields)
        if validation_error:
            return error_response(
                message='请求参数错误',
                error=validation_error,
                status_code=400
            )
        
        # 生成内容
        result = chat_service.generate_marketing_plan(
            requirement_id=data['requirement_id'],
            session_id=data['session_id'],
            user_message=data.get('message', '')
        )
        
        return success_response(
            data={
                'content': result['content'],
                'session_id': result['session_id'],
                'response_id': result['response_id']
            },
            message='内容生成成功'
        )
        
    except ValueError as e:
        return error_response(
            message='内容生成失败',
            error=str(e),
            status_code=400
        )
    except Exception as e:
        logging.error(f"生成内容失败: {str(e)}")
        return error_response(
            message='内容生成失败',
            error=str(e)
        )